<template>
  <div class="app-container">
    <div class="filter-container">
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="12" :lg="16" :xl="16">
          <span v-for="(item, index) in query" :key="index">
            <el-input v-if="item.type === 'input'"  class="filter-item" clearable v-model="listQuery[index].value" :placeholder="item.label"  @keyup.enter.native="fetchListData"></el-input>
            <el-select v-if="item.type === 'select' && item.options"  class="filter-item" clearable v-model="listQuery[index].value"  :placeholder="item.label" @change="fetchListData">
              <el-option v-for="(selectItem, selectIndex) in options[item.options.name + 'Options']" :key="selectIndex + '_' + index" :value="selectItem[item.options.key]" :label="selectItem[item.options.value]"></el-option>
            </el-select>
            <el-date-picker v-if="item.type === 'date'"  class="filter-item-time" clearable v-model="listQuery[index].value" format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss" :default-time="['00:00:00.000', '23:59:59.999']" @change="fetchListData" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </span>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8" style="text-align: right">
          <el-button  class="filter-button" v-waves icon="el-icon-back" @click="$router.back()">返回</el-button>
          <el-button  class="filter-button" v-waves type="primary" icon="el-icon-search" @click="fetchListData">搜索</el-button>
          <el-button  class="filter-button" v-waves type="primary" icon="el-icon-edit" v-permission="['sysUser:add']" @click="handleCreate">新建</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="table-container">
      <base-list ref="table" :url="url + '/list'" :query="listQuery" :columns="columns" :format="format" :row-click="handleDetail" :sort-change="handelChangeSortBy">
        <template slot="status" slot-scope="scope">
          <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
          <el-tag v-if="scope.row.status === 2" type="warning">禁用</el-tag>
        </template>
        <template slot="actions" slot-scope="scope">
          <el-button  v-waves v-permission="['sysUser:edit']" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button  v-waves v-if="scope.row.status === 1" v-permission="['sysUser:disable']" type="warning" @click="handleStatus(scope.row.id, 2)">禁用</el-button>
          <el-button  v-waves v-if="scope.row.status === 2" v-permission="['sysUser:enable']" type="success" @click="handleStatus(scope.row.id, 1)">启用</el-button>
          <el-button  v-waves v-permission="['sysUser:delete']" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>

          <el-button  v-for="(item, index) in buttons" :key="index" v-waves :v-permission="item.permission"  :type="item.type" @click="item.func(scope.$index, scope.row)">重置密码</el-button>
        </template>
      </base-list>
      <el-dialog :title="dialogTextMap[dialogStatus]" :visible.sync="createDialogVisible" :width="$store.state.app.device === 'mobile' ? '100%' : '60%'">
        <el-form ref="dataForm" :rules="rules" :model="temp" label-width="100px" label-suffix=": " :inline="true" >
          <el-form-item v-for="(item, index) in columns" v-if="item.inForm" :key="index" :label="item.label" :prop="item.key">
            <el-input  v-if="item.formType === 'input'" class="form-item" :disabled="dialogStatus === 'detail'" v-model="temp[item.key]" :placeholder="item.label"></el-input>
            <el-select  v-if="item.formType === 'select'" :multiple="item.multiple" class="form-item" :disabled="dialogStatus === 'detail'" v-model="temp[item.key]" :placeholder="item.label">
              <el-option v-for="(selectItem, selectIndex) in options[item.options.name + 'Options']" :key="selectIndex + '_' + index" :value="selectItem[item.options.key]" :label="selectItem[item.options.value]"></el-option>
            </el-select>
            <upload-image v-if="item.formType === 'image'" class="form-item" :ref="'media_' + item.key" @uploadSuccess="mediaChange" :fileUrl="temp[item.key]" :columnName="item.key"></upload-image>
            <upload-video v-if="item.formType === 'video'" class="form-item" :ref="'media_' + item.key" @uploadSuccess="mediaChange" :fileUrl="temp[item.key]" :columnName="item.key"></upload-video>
            <el-input-number v-if="item.formType === 'number'"  clearable class="form-item" v-model="temp[item.key]" placeholder="${field.comment}"></el-input-number>
            <el-date-picker v-if="item.formType === 'datetime'"  clearable class="form-item" v-model="temp[item.key]" type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" placeholder="${field.comment}"></el-date-picker>
            <el-time-select v-if="item.formType === 'time'"  clearable class="form-item" v-model="temp[item.key]" :picker-options="{ start: '00:00', step: '00:15', end: '24:00' }" placeholder="${field.comment}"></el-time-select>
            <el-date-picker v-if="item.formType === 'date'"  clearable class="form-item" v-model="temp[item.key]" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="${field.comment}"></el-date-picker>
            <el-input  v-if="item.formType === 'double'" clearable class="form-item" v-model="temp[item.key]" placeholder="${field.comment}"  onkeyup="value=value.replace(/[^\d\.]/g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.')"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" v-if="dialogStatus !== 'detail'">
          <el-button  v-waves @click="createDialogVisible = false">取消</el-button>
          <el-button  v-waves type="primary" v-permission="['sysUser:add' || 'sysUser:edit ']" @click="dialogStatus==='create'?handleAdd():handleUpdate()">提交</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import waves from '@/directive/waves' // waves directive
  import { create, update, deleteById, updateSate, changeSort, getOptions, exportExcel} from '@/api/common'
  import BaseList from '@/components/BaseList'
  import TreeTableList from '@/components/TreeTableList'
  import UploadVideo from '@/components/UploadVideo'
  import UploadImage from '@/components/UploadImage'
  export default {
    components: { BaseList, TreeTableList, UploadVideo, UploadImage },
    directives: { permission, waves },
    props: {
      isTree: {type: Boolean, default: false},
      url: {type: String, default: ''},
      moduleName: {type: String, default: ''},
      query: { type: Array, default: () => [] },
      columns: { type: Array, default: () => [] },
      sortChange: { type: Function, default: () => {} },
      dateDel: { type: Function, default: () => {} },
      rowClick: { type: Function, default: () => {} },
      append: { type: Object, default: () => {} },
      spanColumn: { type: String },
      entity: {type: Object,default: () => {return {id: undefined}}},
      rules: { type: Object, default: () => {} },
      optionNames: { type: Array, default: () => [] },
      buttons: { type: Array, default: () => [] },
    },
    data() {
      return {
        dialogTextMap: {update: '编辑',create: '新建', detail: '详情'},
        options: {},
        temp:{},
        dialogStatus: '',
        createDialogVisible: false,
        listQuery:[],
        format: {
          index: (data, index) => { return index + 1 },
        },
      }
    },
    created() {
      const allOptions = JSON.parse(localStorage.getItem('allOptions'))
      this.query.forEach(e => {
        this.listQuery.push(Object.assign({},e,{value: undefined}))
      })
      this.optionNames.forEach(e => {
        if (e.inDict) {
          this.$set(this.options,e.name+'Options',allOptions[e.name+'Options'])
        } else if (e.module) {
          getOptions('/' + e.module + '/' + e.name +'/options',undefined).then(res => {
            this.$set(this.options,e.name+'Options',res.data)
          })
        } else {
          this.$set(this.options,e.name+'Options',e.value)
        }
      })
      this.columns.forEach(e => {
        if (e.options) {
          if (e.multiple) {
            this.$set(this.format,e.key,(data,index) => {return this.options[e.options.name + 'Options'].filter(o => data[e.key].includes(o[e.options.key])).map(o => o[e.options.value])})
          } else {
            this.$set(this.format,e.key,(data,index) => {return this.options[e.options.name + 'Options'].find(o => o.id === data[e.key])[e.options.value]})
          }
        }
      })
    },
    mounted() {
      this.fetchListData()
    },
    methods: {
      fetchListData() {
        this.$refs.table.fetchData(1)
      },
      reloadListData() {
        this.$refs.table.fetchData()
      },
      mediaChange(val, index, column) {
        this.temp[column] = val;
      },
      handleDetail(row, column, event) {
        if (column.property !== 'actions') {
          this.handleEdit(-1,row)
          this.dialogStatus = 'detail'
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.createDialogVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleEdit(index, val) {
        this.temp = Object.assign({}, val)
        this.dialogStatus = 'update'
        this.createDialogVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleAdd() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const queryData = Object.assign({}, this.temp)
            queryData.status = Number(queryData.status)
            create(queryData).then(() => {
              this.fetchListData()
              this.createDialogVisible = false
              this.$notify.success('创建成功！')
            })
          }
        })
      },
      handleUpdate() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData.timestamp = +new Date(tempData.timestamp)
            update(tempData).then(() => {
              this.reloadListData()
              this.createDialogVisible = false
              this.$notify.success('更新成功！')
            })
          }
        })
      },
      handleDelete(index, val) {
        const self = this
        this.$confirm('确定要删除该' + this.moduleName + '？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delete(this.url + '/delete/' + val.id).then(() => {
            self.reloadListData()
            self.$notify.success('删除成功！')
          })
        }).catch(() => {})
      },
      handleStatus(id, status) {
        const self = this
        this.$confirm('确定要'+['', '启用','禁用'][status]+'该' + this.moduleName + '？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateSate(id, status).then(() => {
            self.createDialogVisible = false
            self.reloadListData()
            self.$notify.success('操作成功！')
          })
        }).catch(() => {return})
      },
      handleExport() {
        exportExcel({conditions:this.listQuery})
      },
      handelChangeSortBy(oneId, oneSortBy, twoId, twoSortBy) {
        const sortChangeData = { oneId: oneId, oneSortBy: oneSortBy, twoId: twoId, twoSortBy: twoSortBy }
        changeSort(this.url + '/sort',sortChangeData).then(res => {
          if (!res.code) {
            this.fetchListData()
          }
        })
      },
    }
  }
</script>

